package core

import (
	"go-tun2socks/common/log"
	"net"
	"sync"
)

type TCPWriter interface {
	Write([]byte) (int, error)
	Read([]byte) (int, error)
	Close() error
	RestartTimeouts()
}


var tcpMutex = &sync.Mutex{}

type tcpReaderWriter struct {
	tcpConn  net.Conn
	//udpConnect  net.UDPConn
	//ctx 		context.Context
	//cancel 		context.CancelFunc
}

// addr格式： "127.0.0.1:1080"
func NewTCPWriter(addr string) TCPWriter {
	tcpConnect , err := net.Dial("tcp", addr)
	if err != nil {
		log.Fatalf("与%s之间的TCP连接建立失败", addr)
		panic("TCP连接建立失败")
	}
	//ctx, cancel := context.WithCancel(context.Background())
	return &tcpReaderWriter{
		tcpConn : tcpConnect,
	}
}

func (writer *tcpReaderWriter) Write(data []byte) (int, error){
	if len(data) == 0 {
		return 0, nil
	}

	ipversion, err := peekIPVer(data)
	if err != nil {
		return 0, err
	}
	nextProto, err := peekNextProto(ipversion, data)
	if err != nil {
		return 0, err
	}
	log.Infof("ipv = %d,tcpv = %d, len = %d\n", ipversion, nextProto, len(data))
	tcpMutex.Lock()
	defer tcpMutex.Unlock()

	//var header_size int
	//if nextProto == proto_udp {
	//	header_size = 20 + 8
	//} else {
	//	header_size = 40
	//}

	//pkt := make([]byte, len(data))
	//copy(pkt[:],data[:header_size])
	//copy(pkt[header_size:],data[:])
	return writer.tcpConn.Write(data)
}

func (writer *tcpReaderWriter) Read(data []byte) (int, error){
	return writer.tcpConn.Read(data)
}


func (writer *tcpReaderWriter) Close() error{
	return writer.tcpConn.Close()
}

func (writer *tcpReaderWriter) RestartTimeouts(){

}
